/*
  File: InitializerHelper.cs
  Author: rcrxy
  CreateTime: 2025/07/03 16:48

  Description:
*/

using Microsoft.EntityFrameworkCore;
using StudentVideo.Data;
using StudentVideo.Data.Entities;
using StudentVideo.Shared.Enums;
using StudentVideo.Utils;

namespace StudentVideo.Helper;

/// <summary>
/// 内容初始化
/// </summary>
/// <param name="context"></param>
/// <param name="redis"></param>
public class InitializerHelper(AppDbContext context, RedisDbHelper redis) {
   private readonly AppDbContext _context = context;
   private readonly RedisDbHelper _redis = redis;

   public async Task Invoke() {
      await AdminUser();
   }

   /// <summary>
   /// 初始化管理员用户
   /// </summary>
   /// <returns></returns>
   private async Task AdminUser() {
      _context.Database.EnsureCreated();

      // 查询是否存在管理员角色
      var adminRole = await _context.Roles.FirstOrDefaultAsync(e => e.Type == RoleTypeEnum.Admin);

      if (adminRole is null) {
         adminRole = new RoleEntity() {
            Name = "administrator",
            Type = RoleTypeEnum.Admin,
            Description = "管理员"
         };

         await _context.Roles.AddAsync(adminRole);
      }

      // 查询是否存在管理员用户
      bool hasAdminUser = await _context.UserRoleMaps
         .AnyAsync(map => map.RoleId == adminRole.Id);

      if (hasAdminUser)
         return;

      var salt = PasswordHasher.GenerateSalt();
      var pwd = PasswordHasher.HashPassword("123456", salt);

      UserEntity adminUser = new() {
         Nickname = "管理员",
         Username = "admin",
         Salt = salt,
         Password = pwd,
         Gender = GenderEnum.Male
      };

      await _context.Users.AddAsync(adminUser);

      await _context.UserRoleMaps.AddAsync(new() {
         RoleId = adminRole.Id,
         Role = adminRole,
         UserId = adminUser.Id,
         User = adminUser
      });

      await _context.SaveChangesAsync();
   }
}
